import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import MarkdownIt from 'markdown-it'

export function useChat(isAuthenticatedRef, authTokenRef, handleUnauthorizedFunc, showLoginModalRef) {
  const md = new MarkdownIt()
  const isAuthenticated = isAuthenticatedRef
  const authToken = authTokenRef
  const handleUnauthorized = handleUnauthorizedFunc
  const showLoginModal = showLoginModalRef

  const messages = ref([])
  const apiMessages = ref([])
  const inputMessage = ref('')
  const loading = ref(false)
  const chatContainerRef = ref(null)
  const currentModel = ref('deepseek-chat')
  const isMobileMenuOpen = ref(false)
  const currentStreamingMessage = ref('')
  const currentReasoningContent = ref('')
  const conversations = ref([])
  const currentConversationId = ref(null)
  const loadingConversations = ref(false)
  const isMobileView = ref(window.innerWidth <= 768)

  const modelOptions = [
    { label: 'DeepSeek Chat', value: 'deepseek-chat' },
    { label: 'DeepSeek Reasoner', value: 'deepseek-reasoner' }
  ]

  const fetchWithAuth = async (url, options = {}) => {
    const token = authToken.value

    if (!token) {
      console.error('No auth token available for request to:', url)
      throw new Error('认证令牌不可用，请重新登录')
    }

    if (typeof token !== 'string' || token.length < 20) {
      console.error('Invalid token format:', typeof token, token?.length)
      throw new Error('认证令牌格式无效，请重新登录')
    }

    console.log(`Making authenticated request to ${url} with token: ${token.substring(0, 10)}...`)

    const headers = {
      ...options.headers,
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    }

    const response = await fetch(url, { ...options, headers })

    if (response.status === 401) {
      console.error('Unauthorized request, token may be invalid')
      if (handleUnauthorized) {
        handleUnauthorized()
      }
      throw new Error('认证已过期，请重新登录')
    }

    return response
  }

  const scrollToBottom = async () => {
    await nextTick()
    if (chatContainerRef.value) {
      chatContainerRef.value.scrollTop = chatContainerRef.value.scrollHeight
    }
  }

  const renderMarkdown = (content) => {
    return md.render(content || '')
  }

  const handleStreamResponse = async (response) => {
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let accumulatedData = ''

    currentStreamingMessage.value = ''
    currentReasoningContent.value = ''

    try {
      while (true) {
        const { done, value } = await reader.read()
        if (done) break

        const chunk = decoder.decode(value, { stream: true })
        accumulatedData += chunk

        try {
          const lines = accumulatedData.split('\n').filter(line => line.trim())
          accumulatedData = ''

          for (const line of lines) {
            const data = JSON.parse(line)
            if (data.error) {
              ElMessage.error(data.error)
              continue
            }

            if (data.type === 'reasoning') {
              currentReasoningContent.value += data.content
              const lastMessage = messages.value[messages.value.length - 1]
              if (lastMessage && lastMessage.role === 'assistant') {
                lastMessage.reasoning_content = currentReasoningContent.value
              }
            } else if (data.type === 'content') {
              currentStreamingMessage.value += data.content
              const lastMessage = messages.value[messages.value.length - 1]
              if (lastMessage && lastMessage.role === 'assistant') {
                lastMessage.content = currentStreamingMessage.value
                await nextTick()
              }
            } else if (data.type === 'conversation_id') {
              currentConversationId.value = data.conversation_id
              console.log('Conversation saved with ID:', currentConversationId.value)
            }
          }
          await scrollToBottom()
        } catch (e) {
          console.error('Error processing chunk:', e)
          continue
        }
      }
    } catch (error) {
      console.error('Stream error:', error)
      throw error
    }
  }

  function normalizeMessages(messages) {
    if (!Array.isArray(messages)) return []
    const result = []
    let lastRole = null
    for (const msg of messages) {
      if (!msg.role || !msg.content) continue
      if (msg.role === lastRole) continue
      result.push(msg)
      lastRole = msg.role
    }
    return result
  }

  const sendMessage = async () => {
    if (!isAuthenticated.value) {
      console.log("User not authenticated, showing login modal.");
      showLoginModal.value = true
      return
    }

    const trimmedMessage = inputMessage.value.trim()
    if (!trimmedMessage) {
      ElMessage.warning('请输入消息')
      return
    }

    const userMessage = trimmedMessage
    const originalMessage = inputMessage.value
    inputMessage.value = ''

    const userMessageObj = {
      role: 'user',
      content: userMessage
    }

    const messagesForApi = [...apiMessages.value, userMessageObj]
    const finalApiMessages = normalizeMessages(messagesForApi)

    const firstNonSystemIndex = finalApiMessages.findIndex(msg => msg.role !== 'system')
    if (finalApiMessages.length === 0 || (firstNonSystemIndex !== -1 && finalApiMessages[firstNonSystemIndex].role !== 'user')) {
      console.error('Invalid message history for API:', finalApiMessages)
      ElMessage.error('无法发送消息：消息历史格式错误，必须以用户消息开始。')
      inputMessage.value = originalMessage
      return
    }

    messages.value.push(userMessageObj)

    loading.value = true
    currentStreamingMessage.value = ''
    currentReasoningContent.value = ''

    messages.value.push({
      role: 'assistant',
      content: '',
      reasoning_content: currentModel.value === 'deepseek-reasoner' ? '' : null
    })

    await scrollToBottom()

    try {
      if (!authToken.value) {
        throw new Error('认证令牌不可用，请重新登录')
      }

      console.log(`Using auth token: ${authToken.value.substring(0, 10)}...`)

      const payload = {
        messages: finalApiMessages,
        model: currentModel.value,
        conversation_id: currentConversationId.value
      }

      console.log('Sending chat request with payload:', payload)

      const response = await fetchWithAuth('/api/chat', {
        method: 'POST',
        body: JSON.stringify(payload)
      })

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.error?.message || error.error || '请求失败')
      }

      await handleStreamResponse(response)

      apiMessages.value = [...finalApiMessages, {
        role: 'assistant',
        content: currentStreamingMessage.value,
        ...(currentReasoningContent.value ? { reasoning_content: currentReasoningContent.value } : {})
      }]

      await loadConversations()
    } catch (error) {
      console.error('Error sending message:', error)
      ElMessage.error(error.message || '发送消息失败')

      if (error.message !== '请输入消息') {
        inputMessage.value = originalMessage
      }

      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && lastMessage.role === 'assistant' && !lastMessage.content) {
        messages.value.pop()
      }
    } finally {
      loading.value = false
    }
  }

  const loadConversations = async () => {
    console.log('loadConversations: Function start. Assuming authenticated by caller.');
    try {
      loadingConversations.value = true;
      console.log('loadConversations: Loading conversations...');

      const response = await fetchWithAuth('/api/conversations');
      console.log('loadConversations: API request finished.');

      if (!response.ok) {
        const errorText = await response.text()
        throw new Error(`Failed to load conversations: ${response.status} - ${errorText}`)
      }

      const data = await response.json()
      console.log(`Loaded ${data.conversations?.length || 0} conversations`)

      conversations.value = data.conversations || []

      if (conversations.value.length === 0 && data.welcome_message) {
        messages.value = [{
          role: 'assistant',
          content: data.welcome_message
        }]
      }
    } catch (error) {
      console.error('loadConversations: Error loading conversations:', error);
      ElMessage.error('加载对话历史失败: ' + error.message);
    } finally {
      loadingConversations.value = false;
      console.log('loadConversations: Function end.');
    }
  }

  const loadConversation = async (conversationId) => {
    try {
      loading.value = true
      const response = await fetch(`/api/conversations/${conversationId}`, {
        headers: {
          'Authorization': `Bearer ${authToken.value}`
        }
      })
      if (!response.ok) {
        throw new Error('Failed to load conversation')
      }
      const data = await response.json()

      currentConversationId.value = conversationId
      messages.value = data.messages
      apiMessages.value = data.messages

      ElMessage.success('对话加载成功')
      await nextTick()
      await scrollToBottom()
    } catch (error) {
      console.error('Error loading conversation:', error)
      ElMessage.error('加载对话失败')
    } finally {
      loading.value = false
    }
  }

  const deleteConversation = async (conversationId) => {
    try {
      const response = await fetch(`/api/conversations/${conversationId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${authToken.value}`
        }
      })

      if (!response.ok) {
        throw new Error('Failed to delete conversation')
      }

      if (conversationId === currentConversationId.value) {
        clearChat()
      }

      await loadConversations()
      ElMessage.success('对话已删除')
    } catch (error) {
      console.error('Error deleting conversation:', error)
      ElMessage.error('删除对话失败')
    } finally {
      loading.value = false
    }
  }

  const clearChat = () => {
    messages.value = []
    apiMessages.value = []
    isMobileMenuOpen.value = false
    currentConversationId.value = null

    messages.value.push({
      role: 'assistant',
      content: '欢迎使用 AI 问答助手！有什么我可以帮你的吗？'
    })
  }

  onMounted(() => {
    console.log('useChat composable mounted')

    window.addEventListener('resize', () => {
      isMobileView.value = window.innerWidth <= 768
      if (!isMobileView.value) {
        isMobileMenuOpen.value = false
      }
    })
  })

  return {
    messages,
    inputMessage,
    loading,
    chatContainerRef,
    currentModel,
    isMobileMenuOpen,
    currentStreamingMessage,
    currentReasoningContent,
    modelOptions,
    sendMessage,
    clearChat,
    renderMarkdown,
    conversations,
    currentConversationId,
    loadingConversations,
    loadConversations,
    loadConversation,
    deleteConversation,
    isMobileView
  }
}